package cc.bookcloud.tool.ocr.util;

import cn.hutool.core.codec.Base64;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
 * @Desc: @todo
 * @Version: 2.0
 * @Author: John Goo
 * @Date: 2024/07/11 11:17
 **/
@Slf4j
public class RSAUtil {

    /**
     * 加密算法.
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * RSA秘钥.
     */
    public static String rsaPrivateKey = "B+7PxcVSjOCnJt45lDjfKsuVA8UMrFBkrRIi";

    /**
     * 赋值.
     *
     * @param rsaPrivateKey 配置的私钥
     */
    @Value("${auth.rsa.privateKey:}")
    public void setRsaPrivateKey(String rsaPrivateKey) {
        this.rsaPrivateKey = rsaPrivateKey;
    }

    /**
     * 私钥解密.
     *
     * @param text             待解密的文本
     * @return 解密后的文本
     */
    public static String decryptByPrivateKey(String text) {
        return decryptByPrivateKey(rsaPrivateKey, text);
    }

    /**
     * 私钥解密.
     *
     * @param privateKeyString 私钥
     * @param text             待解密的文本
     * @return 解密后的文本
     */
    public static String decryptByPrivateKey(String privateKeyString, String text) {
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decode(privateKeyString));
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] result = cipher.doFinal(Base64.decode(text));
            return new String(result);
        } catch (Exception e) {
            log.error("decryptByPrivateKey error", e);
            return null;
        }
    }

    /**
     * 公钥加密.
     *
     * @param publicKeyString 公钥
     * @param text            待加密的文本
     * @return 加密后的文本
     */
    public static String encryptByPublicKey(String publicKeyString, String text) {
        try {
            X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decode(publicKeyString));
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] result = cipher.doFinal(text.getBytes());
            return Base64.encode(result);
        } catch (Exception e) {
            log.error("encryptByPublicKey error", e);
            return null;
        }
    }

    /**
     * 构建RSA密钥对.
     *
     * @return 生成后的公私钥信息
     */
    public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        String publicKeyString = Base64.encode(rsaPublicKey.getEncoded());
        String privateKeyString = Base64.encode(rsaPrivateKey.getEncoded());
        return new RsaKeyPair(publicKeyString, privateKeyString);
    }

    /**
     * RSA密钥对对象.
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class RsaKeyPair {
        /**
         * 公钥.
         */
        private String publicKey;

        /**
         * 私钥.
         */
        private String privateKey;
    }


    public static void main(String[] args) throws NoSuchAlgorithmException {
        // 生成公私钥对
        RSAUtil.RsaKeyPair keyPair = RSAUtil.generateKeyPair();
        System.out.println(" 公钥：： keyPair.getPublicKey() = " + keyPair.getPublicKey());
        System.out.println(" 私钥：:  keyPair.getPrivateKey() = " + keyPair.getPrivateKey());
        // 公钥加密
        String text = "zhu";
        String encryptStr = RSAUtil.encryptByPublicKey(keyPair.getPublicKey(), text);
        System.out.println("密文 = " + encryptStr);
        // 私钥解密
        String plain = RSAUtil.decryptByPrivateKey(keyPair.getPrivateKey(), encryptStr);
        System.out.println("明文 = " + plain);
    }
}

